"""

@Time: 2021/2/5 19:18
@Author:
@File: fault_search_controller.py
"""
from fastapi import APIRouter, Depends, Query
from elasticsearch import AsyncElasticsearch
from elasticsearch_dsl import Search
from typing import Optional

from dependencies import verify_token, get_es
from models.dto import RESTfulModel
from config import es_conf

search_router = APIRouter(tags=['search'])


@search_router.get('/global_search',
                   response_model=RESTfulModel,
                   dependencies=[Depends(verify_token), ],
                   summary='使用关键字进行全局的故障检索',
                   description="根据给定的关键字在 ES 中进行全局的故障检索，并将检索命中的全部数据返回")
async def global_faulty_search(keyword: str = Query(..., min_length=1, description='搜索的关键字'),
                               _from: Optional[int] = Query(0, ge=0, description='搜索结果的开始位置'),
                               size: Optional[int] = Query(10, gt=0, description='搜索结果的大小'),
                               es_client: AsyncElasticsearch = Depends(get_es)):
    match_fields = [
        'brief', 'fault_name', 'fault_site'
    ]
    search = Search().query('multi_match', query=keyword, fields=match_fields)  # 采用多重匹配
    search = search[_from: size]
    es_resp = await es_client.search(index=es_conf.INDEX_NAME, body=search.to_dict())
    return RESTfulModel(code=0, data=es_resp['hits']['hits'])
